package ch.esn.client.presenter;

import ch.esn.client.MainEventBus;
import ch.esn.client.service.UserServiceAsync;
import ch.esn.client.view.LoginEnsureView;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.mvp4g.client.annotation.InjectService;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.BasePresenter;

@Presenter(view = LoginEnsureView.class)
public class LoginPresenter extends BasePresenter<LoginEnsureView, MainEventBus> {

	private UserServiceAsync userService;

	private String appURL = com.google.gwt.user.client.Window.Location.getHref();

	public void onLogout() {
		userService.getLogoutURL(appURL, new AsyncCallback<String>() {

			public void onFailure(Throwable caught) {
				com.google.gwt.user.client.Window.alert("Error while retrieving logout URL!");
			}

			public void onSuccess(String result) {
				com.google.gwt.user.client.Window.open(result, "_self", null);
			}
		});
	}

	public void onShowLogin() {
		userService.getLoginURL(appURL, new AsyncCallback<String>() {

			public void onFailure(Throwable caught) {
				com.google.gwt.user.client.Window.alert("Error while retrieving if user is logged in!");
			}

			public void onSuccess(String result) {
				com.google.gwt.user.client.Window.open(result, "_self", null);
			}
		});
	}

	public void onStart() {
		userService.isUserLoggedIn(new AsyncCallback<Boolean>() {

			public void onFailure(Throwable caught) {
				com.google.gwt.user.client.Window.alert("Error while retrieving if user is logged in!");
			}

			public void onSuccess(Boolean userIsLogged) {
				if (userIsLogged) {
					eventBus.initApp();
				} else {
					eventBus.showLogin();
				}
			}
		});
	}

	@InjectService
	public void setUserService(UserServiceAsync userService) {
		this.userService = userService;
	}

}
